package com.imfondof.mvc_mvp_mvvm.normal;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.imfondof.mvc_mvp_mvvm.R;
import com.imfondof.mvc_mvp_mvvm.bean.Account;
import com.imfondof.mvc_mvp_mvvm.callback.MCallback;

import java.util.Random;

public class NormalActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText mEtInput;
    private Button mBtGetAccount;
    private TextView mTvResult;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_normal);

        initView();
    }

    private void initView() {
        mEtInput = findViewById(R.id.et_input);
        mBtGetAccount = findViewById(R.id.bt_get_data);
        mTvResult = findViewById(R.id.tv_result);
        mBtGetAccount.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        getAccountData(getUserInput(), new MCallback() {
            @Override
            public void onSuccess(Account account) {
                showSuccess(account);
            }

            @Override
            public void onFailed() {
                showFailed();
            }
        });
    }

    private String getUserInput() {
        return mEtInput.getText().toString();
    }

    private void showSuccess(Account account) {
        mTvResult.setText(account.getName() + "|" + account.getLevel());
    }

    private void showFailed() {
        mTvResult.setText("无数据");
    }

    //模拟数据库查询操作
    private void getAccountData(String userInput, MCallback callback) {
        Random random = new Random();
        boolean isSuccess = random.nextBoolean();
        if (isSuccess) {
            Account account = new Account(userInput, 100);
            callback.onSuccess(account);
        } else {
            callback.onFailed();
        }
    }
}
